package org.cms;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClients;
import org.cms.annotation.FourSquare;
import org.cms.call.GetCheckinsCall;
import org.cms.dao.IDao;
import org.cms.entities.CheckIn;
import org.cms.raw.CheckInRaw;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import javax.ejb.EJB;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

/**
 * Facade for retrieving checkin data from FOURSQUARE service
 */
@FourSquare
public class FourSquareFacade implements ILocationService<CheckIn> {

    private final Logger logger = Logger.getLogger("org.cms.FourSquareFacade");
    private PropertiesHandler propertiesHandler = new PropertiesHandler("location_tokens.properties");
    private String authToken = "undefined";
    private static final String apiVersion = "20140806";

    @EJB(beanName = "CheckInDao")
    IDao<CheckIn,String> checkInDao;

    public List<CheckIn> getUserPlaces() {

        HttpClient httpclient = HttpClients.createDefault();
        List<CheckIn> allCheckins = new ArrayList<CheckIn>();

        try {
            for (String key : propertiesHandler.stringPropertyNames()) {
                this.authToken = propertiesHandler.getProperty(key);


                GetCheckinsCall checkinsCall = new GetCheckinsCall(this.authToken, this.apiVersion, httpclient).invoke();

                logger.info("executing request to " + checkinsCall.getRequest());

                String output = checkinsCall.getResponseContentAsString();
                JSONObject json = new JSONObject(output);
                JSONArray checkinsArray = json.getJSONObject("response").getJSONObject("checkins").getJSONArray("items");
                System.out.println(checkinsArray.length());

                Gson gson = new GsonBuilder().create();

                for (int i = 0; i < checkinsArray.length(); i++) {
                    JSONObject checkin = checkinsArray.getJSONObject(i);
                    CheckInRaw cr = gson.fromJson(checkin.toString(), CheckInRaw.class);
                    CheckIn ci = CheckinMapper.map(cr);
                    allCheckins.add(ci);

                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            httpclient.getConnectionManager().shutdown();
        }

        for (CheckIn ci : allCheckins) {
            checkInDao.merge(ci);
            logger.info("saved in the DB");
        }
        return allCheckins;

    }

}
